package com.etc.reflectdemo;

import java.lang.reflect.Field;

/**
 * @author: knowno
 * @create: 2024-09-18 14:14
 * @Version 1.0
 **/
public class TestField {
    public static void main(String[] args) throws NoSuchFieldException, InstantiationException, IllegalAccessException {

        Class<Person> personClass = Person.class;

        //构造一个person对象
        Person person = personClass.newInstance();
        //得到所有字段
        Field[] declaredFields = personClass.getDeclaredFields();

        //得到字段，要给这个字段赋值=>分别获取不同的字段
        //获取单个字段
        Field ageField = personClass.getDeclaredField("age");

        //class com.etc.reflectdemo.TestField cannot access a member of class com.etc.reflectdemo.Person with modifiers "private"
        ageField.setAccessible(true);

        //赋值的方法(Person对象,值)
        ageField.setInt(person,20);

        System.out.println(person);



    }
}
